<?php

namespace app\facility\controller;

use think\Db;
use think\worker\Server;


class Tcpworker extends Server
{
    protected $socket = 'tcp://0.0.0.0:8900';
    protected $processes = 1;

    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        try {
            $macMessage = new MacMessageConsume;
            $res = $macMessage->process_message($data);
            echo "data:" . $data . "\n";
            $connection->send("ok");
        } catch (\Think\Exception  $outExcep) {
            write_log("处理数据出异常了：" . $outExcep->getMessage(), 2);
        }
    }
    function mkdirs($dir, $mode = 511)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }

        if (!mkdirs(dirname($dir), $mode)) {
            return false;
        }

        return @mkdir($dir, $mode);
    }

    function write_log($content, $type = 1)
    {
        $type_name = "info";
        if ($type == 2) {
            $type_name = "error";
        } else if ($type == 3) {
            $type_name = "other";
        }
        $t = time();
        $base_path = ROOT_PATH . 'logs/' . $type_name . '/' . date("Y-m", $t) . '/' . date("d", $t) . '/' . date("H", $t);
        mkdirs($base_path);
        $filename = $base_path . '/' . date("i") . ".log";
        $Ts = fopen($filename, "a+");
        $content = "[" . date("Y-m-d H:i:s", $t) . ']：' . $content;
        fputs($Ts, "\r\n" . $content);
        fclose($Ts);
    }


    public function onConnect($connection)
    {

        echo "New Connection\n";
    }

    public function onClose($connection)
    {

        echo "Connection closed\n";
    }

    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }

    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        echo "onWorkerStart___\n";
    }
}
